package security;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Random;

import sd1.security.PrivateKey;
import sd1.security.PublicKey;

public class KeyManager
{
	private static KeyManager instance;
	
	public static synchronized KeyManager getInstance() {
		if( instance == null)
			instance = new KeyManager();
		return instance;
	}
	private static PrivateCert pvc;
	private static PublicCert pbc;
	private static PublicKey cakey;
	private static PrivateKey privkey;
	private static int pattern;
	
	public static void makePublicCert(String name){
    	pvc = null;
    	try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(name+"_Cert"));
			pvc = (PrivateCert) ois.readObject();
			ois.close();
		} catch (IOException e) {
			System.out.println("Não conseguiu escrever no ficheiro!");
		}catch (ClassNotFoundException e) {
			System.out.println("Erro na leitura de objecto!");
		}
		pbc = new PublicCert(pvc.getName(), pvc.getPublicKey(), pvc.getDigest());
		try {
			cakey = PublicKey.createKey(pvc.getCAKey());
			privkey = PrivateKey.createKey(pvc.getPrivateKey());
		} catch (Exception e) {
			System.out.println("Falha na criação de chaves!");
		}
		
		
		//Just for hash:
		Random r = new Random();
		pattern = r.nextInt();
    }
	
	public PublicCert getPublicCert() {
		return pbc;
	}
	
	public PublicKey getPublicCAKey() {
		return cakey;
	}
	
	public byte[] decript(byte[] coded){
		return privkey.decrypt(coded);
	}
	
	public int getPattern() {
		return pattern;
	}
}